<template>
	<view style="margin-left:10rpx;margin-right: 10rpx;background-color: #F7FFFD; height: 100%;">
		<view v-for="(item , index) in pages" :key="index">
			<!-- 轮播图 -->
			<Banner :image="item.list" v-if="item.type == 'banner'"></Banner>
			<!-- 三公图 -->
			<view v-if="item.type == 'blockMenu3'" class="m-t-b-sm">
				<BlockSan3 :list="item.list"></BlockSan3>
			</view>
			<!-- 店铺信息 -->
			<view v-if="item.type == 'shopItem'">
				<ShopItem :data="item.data"></ShopItem>
			</view>
			<!-- 卡片信息 -->
			<view v-if="item.type == 'grayInfo'">
				<InfoCard :data="item"></InfoCard>
			</view>

			<view v-if="item.type == 'timeSelect'">
				<!-- <timeSelect :data="item"></timeSelect> -->
				<view style=" background-color: white; color: blue;margin-bottom: 10rpx;">
					<scroll-view scroll-x="true">
						<view class="flex w-full">
							<view @click="timeSelectIndexFun(index)" :class="{active:index==timeSelectIndex} "
								style="position: relative;border: 1rpx solid blue;border-radius: 5rpx;"
								class="m-sm p-20" v-for="(itemTime,index2) in item.data" :key="index2">
								<view style="font-size: 30rpx; width: 100rpx;text-align: center;">{{itemTime.time}}小时
								</view>
								<view style="font-size: 23rpx; text-align: center;">{{itemTime.amount}}元</view>
								<view
									style="position: absolute;left: 0;top:-20rpx;background-color: orange;color: white;padding: 3rpx;border-radius: 10rpx">
									套餐</view>
							</view>
						</view>
					</scroll-view>
				</view>
			</view>

			<!-- 支付方式 -->
			<view v-if="item.type == 'radio'" style="margin-top: 10rpx;">
				<InfoCard title="支付方式" :data="item.data">
					<view class="uni-list">
						<radio-group @change="payChange">
							<view v-for="(item, index3) in item.data" :key="item.index3">
								<view>
									<label class="uni-list-cell uni-list-cell-pd">
										<view class="flex">
											<view class="m-r-20">
												<image style="width: 20rpx; height:20rpx" :src="item.image"></image>
											</view>
											<view class="flex">
												<view style="font-weight: bold;">{{item.name}}
													{{item.value ? item.value :''}}
												</view>
												<view v-if="item.help " class="flex"
													style="justify-content: flex-start;">
													<view style="margin-left: 10rpx;"></view>
													<navigator v-if="item.type=='balance'" :url="item.url"
														style="color: blue;">充值
													</navigator>
													<view style="color: gray;">{{item.help}}</view>
												</view>
											</view>
										</view>
										<view>
											<!-- <view>副标题</view> -->
										</view>
										<view>
											<radio :disabled="moneyAmout == '0.00' && item.type =='balance'"
												:value="item.type" :checked="item.type === method" />
										</view>
									</label>
								</view>
								<view>
									<view v-if="item.form && item.type === method">
										<formDiy :data="item.form"></formDiy>
									</view>
								</view>
							</view>

						</radio-group>
					</view>
				</InfoCard>
			</view>

			<view v-if="item.type == 'cardInfo'">
				<InfoCard :title="item.data.title" :data="item.data">
					<uni-list>
						<uni-list-item v-for="(listItem,i) in item.data.list" @click="uniClick(listItem)" link :key="i"
							:show-extra-icon="true" :extra-icon="extraIcon" :title="listItem.name"></uni-list-item>
					</uni-list>
				</InfoCard>
			</view>

			<!-- 下单按钮 -->
			<view v-if="item.type == 'orderPayButton'">
				<view class="w-full p-20"
					style="bottom: 0rpx; position: fixed; display: flex;justify-content: space-between;background-color: white">
					<view>
						<view v-if="method == 'wechat'">
							<view style="display: flex;align-items: center;">
								<view style="color: gray;">预付</view>
								<view style="font-weight: bold;color: red;font-size: 50rpx;">￥{{defaultMoney}}
								</view>
							</view>
							<view style="color: gray;">{{item.data.subTitle}}</view>
						</view>
					</view>
					<view class="flex">
						<!-- 	<picker @change="pickerMoney" :data-data="item.data" :value="moneyIndex"
							:range="item.data.list">
							<button v-if="item.data.isEdit" class="m-l-r-sm" v-show="method == 'wechat'">押金修改</button>
							<view class="uni-input">{{array[index]}}</view>
						</picker> -->
						<button v-show="method == 'wechat' || method == 'balance'" @click="pay"
							class="bg-default color-default" style="margin-right: 30rpx;">付款</button>
					</view>
				</view>
			</view>
		</view>
		<view style="height: 300rpx;"></view>
	</view>
</template>

<script>
	import Banner from "@/components/banner/banner.vue"
	import BlockSan3 from "@/components/menu/blockScan3.vue"
	import ShopItem from "@/components/layout/shopItem.vue"
	import InfoCard from "@/components/layout/infoCard.vue"
	import timeSelect from "@/components/layout/timeSelect.vue"
	import formDiy from "@/components/layout/form.vue"
	import {
		getOrderStore,
		getOrderPay,
		payBalance
	} from '@/utils/http/http.js'
	import fetch from '@/utils/http/fetch.js'

	export default {
		components: {
			Banner,
			BlockSan3,
			ShopItem,
			InfoCard,
			timeSelect,
			formDiy,
		},
		data() {
			return {
				method: 'wechat',
				pages: [],
				requestData: {},
				onloadData: {},
				moneyIndex: 0,
				moneyAmout: '0.00',
				defaultMoney: '',
				onShowItem: {},
				timeSelectIndex: 0,
				extraIcon: {
					color: '#ff0000',
					size: '22',
					type: 'shop'
				}
			}
		},
		async onLoad(options) {
			this.onloadData = options
			// this.loadWxSdk()
		},

		async onShow(options) {
			if (this.pages) {
				uni.hideLoading();
			}
			await this.$onLaunched
			let item = {}
			item.url = 'Order/create'
			item.id = this.onloadData.id
			item.shop_id = this.onloadData.shop_id
			this.onShowItem = item
			let res = await fetch('/api/common/asyncData', 'GET', item)
			this.requestData = res.data;
			this.pages = res.data.pages
			if (res.data.money && res.data.money != '0.00') {
				this.method = 'balance';
				this.moneyAmout = res.data.money
			}
			if (!this.defaultMoney) {
				this.defaultMoney = res.data.defaultMoney;
			}
			// console.log('到了最后一步')
			// return;
		},

		methods: {
			timeSelectIndexFun(index) {
				this.timeSelectIndex = index
			},
			payChange(e) {
				this.method = e.detail.value;
			},
			async balance() {
				const res = await payBalance(this.onloadData)
				console.log(res)
			},
			pickerMoney(e) {
				this.defaultMoney = e.currentTarget.dataset.data.list[e.detail.value];
				this.onloadData.selectMoney = this.defaultMoney
			},
			async pay() {
				// #ifdef H5
				const isWeChat = this.isInWeChat();
				if (isWeChat) {
					this.h5Pay()
				}
				//#endif

				//#ifdef MP
				this.miniAppPay()
				//#endif
			},
			async h5Pay() {
				const orderInfo = await this.doPay()
				WeixinJSBridge.invoke('getBrandWCPayRequest', orderInfo,
					function(res) {
						if (res.err_msg == "get_brand_wcpay_request:ok") {
							// 使用以上方式判断前端返回,微信团队郑重提示：
							//res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
						}
					});
			},
			isInWeChat() {
				const ua = navigator.userAgent.toLowerCase();
				return ua.indexOf('micromessenger') !== -1;
			},
			async doPay() {
				uni.showLoading({
					title: "支付中"
				})
				
				if (this.method == 'balance') {
					this.balance()
					return;
				}
				const res = await getOrderStore(this.onloadData)
				if (res.code != 200) {
					uni.showToast({
						title: res.message,
						icon: 'error'
					})
					return
				}
				
				const orderId = res.data.id
				const payRes = await getOrderPay({
					order_id: orderId
				})
				
				if (payRes.code !== 200) {
					return;
				}
				const orderInfo = {
					appId:payRes.data.appId,
					timeStamp: payRes.data.timestamp,
					nonceStr: payRes.data.nonceStr,
					package: payRes.data.package,
					signType: payRes.data.signType,
					paySign: payRes.data.paySign,
				}
				return orderInfo;

			},
			miniAppPay() {
				let publicConfig = uni.getStorageSync('publicConfig');
				let thatThis = this;
				let templateId = publicConfig.set.wx_notice_code
				uni.requestSubscribeMessage({
					tmplIds: [templateId], // 替换为你的模板ID  
					success(res) {
						const orderInfo =  thatThis.doPay()
						uni.requestPayment({
							"provider": "wxpay", //固定值为"wxpay"
							...orderInfo,
							success: function(res) {
								uni.reLaunch({
									url: '/pages/ball/diy?url=Order/detail&id=' + orderId
								})
								uni.hideLoading()
							},
							fail: function(err) {
								console.log('支付失败:' + JSON.stringify(err));
								uni.hideLoading()
							}
						});
						
						
						if (res['TEMPLATE_ID1'] === 'accept') {
							// 用户同意接收 TEMPLATE_ID1 对应的订阅消息  
							console.log('用户同意接收 TEMPLATE_ID1 订阅消息');
						}
						if (res['TEMPLATE_ID2'] === 'reject') {
							// 用户拒绝接收 TEMPLATE_ID2 对应的订阅消息  
							console.log('用户拒绝接收 TEMPLATE_ID2 订阅消息');
						}
					},
					fail(err) {
						console.error('订阅消息失败', err);
					}
				});
			}

		},


	}
</script>

<style>
	page {
		background-color: #F7FFFD
	}

	.uni-list-cell {
		position: relative;
		display: flex;
		flex-direction: row;
		justify-content: space-between;
		align-items: center;
	}

	.uni-list-cell-pd {
		padding: 11px 15px;
	}

	.uni-list {
		background-color: #fff;
		position: relative;
		width: 100%;
		display: flex;
		flex-direction: column;
	}

	.active {
		background-color: blue;
		color: white;
	}
</style>